﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fly.Common.Linq;
using Newtonsoft.Json;
using RN.ERP.Web.Utilities;

namespace RN.ERP.Web.Person
{
    public partial class ExpertPdf : System.Web.UI.Page
    {
        protected string ImgBrowseUrl
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["ImgBrowseUrl"] != null)
                {
                    return System.Configuration.ConfigurationManager.AppSettings["ImgBrowseUrl"].ToString();
                }
                return string.Empty;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    Initial();
                }
            }
            catch { }
        }
        /// <summary>
        /// 页面初始化
        /// </summary>
        private void Initial()
        {
            string funcCode = string.Empty;////模板Code
            string parameters = string.Empty;////模板动态数据
            string fileName = string.Empty;////文件名称
            Guid empGuid = Guid.Empty;
            if (Request.Params["funcCode"] != null)
            {
                funcCode = Request.Params["funcCode"].Trim();
            }
            if (Request.Params["parameters"] != null)
            {
                parameters = Server.UrlDecode(Request.Params["parameters"].Trim());
            }
            if (Request.Params["fileName"] != null)
            {
                fileName = Request.Params["fileName"].Trim();
            }
            if (Request.Params["empGuid"] != null)
            {
                Guid.TryParse(Request.Params["empGuid"].Trim(), out empGuid);
            }
            ViewState["funcCode"] = funcCode;
            ViewState["parameters"] = parameters;
            ViewState["fileName"] = fileName + ".pdf";
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(parameters) || string.IsNullOrEmpty(funcCode))
            {
                //lblMessage.Visible = true;
            }
            GetEmpManagersList(empGuid,"00");
            GetEmpEmpPosts(empGuid.ToString(), "00");
            GetEmpQualities(empGuid.ToString(), "00");
            GetWorkExperience(empGuid.ToString(), "00");
            GetExpertRelation(empGuid.ToString(), "00");
            GetExpertSpecialityList(empGuid.ToString(), "00");
        }


        /// <summary>
        ///  计算机操作能力 
        /// </summary>
        /// <param name="IsComputer"></param>
        /// <returns></returns>
        protected string GetIsComputerText(string IsComputer)
        {
            string computerText = string.Empty;
            if (!string.IsNullOrEmpty(IsComputer))
            {
                switch (IsComputer.ToString())
                {
                    case "1":
                        computerText = "熟悉";
                        break;
                    case "2":
                        computerText = "简单了解";
                        break;
                    case "3":
                        computerText = "不熟悉";
                        break;
                }
            }
            return computerText;
        }

        /// <summary>
        /// 取得字典数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetGetDictionary(string type, string condition)
        {
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetDictionary(type, condition, "00"));
            }
        }
    
        /// <summary>
        /// 评审资格小
        /// </summary>
        protected Dictionary<string, string> GetPost2
        {
            get
            {
                return GetGetDictionary("post", "");
            }
        }

        /// <summary>
        /// 评审资格大
        /// </summary>
        protected Dictionary<string, string> GetPost1
        {
            get
            {
                return GetGetDictionary("postsub", "-1"); 
            }
        }

        /// <summary>
        /// 专业
        /// </summary>
        //protected Dictionary<string, string> GetMajor
        //{
        //    get
        //    {
        //        return GetGetDictionary("empmajor", "");
        //    }
        //}

        /// <summary>
        /// 学历
        /// </summary>
        protected Dictionary<string, string> GetDegree
        {
            get
            {
                return  GetGetDictionary("empdegree", ""); ;
            }
        }
        
        /// <summary>
        /// 离退信息
        /// </summary>
        protected Dictionary<string, string> GetLiTui
        {
            get
            {
                ////需要配到字典表
                Dictionary<string, string> postSource = new Dictionary<string, string>();
                postSource.Add("1", "在岗");
                postSource.Add("2", "离岗");
                postSource.Add("3", "退休");
                return postSource;
            }
        }

        protected  string GetDataValue(Dictionary<string, string> dict, string str)
        {
            //判断是否存在相应的key并显示   
            if (dict.ContainsKey(str))
            {
                return dict[str];
            }
            return "";
        }

        /// <summary>
        /// 取得人员基本信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="AreaCode"></param>
        private void GetEmpManagersList(Guid empGuid, string areaCode)
        {
            if (empGuid == Guid.Empty)
            {
                return;
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                ModelService.QueryPersonInfoCondition queryCondition = new ModelService.QueryPersonInfoCondition()
                {
                    EmpGuid = new ParameterValue<Guid> { V = empGuid, O = OptEnum.Equal }
                };
                List<ModelService.QueryPersonInfoCondition> query = new List<ModelService.QueryPersonInfoCondition>() { queryCondition };
                string queryStr = JsonConvert.SerializeObject(query);
                var manages = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(client.GetEmpManagersAllList(1, 0, queryStr, areaCode));
                RepEmpInfo.DataSource = manages;
                RepEmpInfo.DataBind();
                if (manages.FirstOrDefault() != null)
                {
                    lblYear.Text = DateTime.Now.Year.ToString();
                    lblMonth.Text = DateTime.Now.Month.ToString();
                    lblDay.Text = DateTime.Now.Day.ToString();
                    var emp = manages.FirstOrDefault();
                    ExportPdf(emp.EmpGuid.ToString(),areaCode,emp.CorpGuid.ToString(),emp.Name);
                }
            }
        }

        /// <summary>
        /// 人员职称信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="AreaCode"></param>
        public void GetEmpEmpPosts(string empGuid, string areaCode)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var list=JsonConvert.DeserializeObject<List<ModelService.Tb_Emp_Post>>(client.GetEmpEmpPosts(empGuid, areaCode));
                RepEmpPost.DataSource = list;
                RepEmpPost.DataBind();
                if (list != null && list.Count > 0)
                {
                    lblZC.Text=GetDataValue(GetPost2, list.First().Post_psZGCode);
                }
            }
        }

        /// <summary>
        /// 人员资格证书查询
        /// </summary>
        private void GetEmpQualities(string empGuid, string areaCode)
        {
            string type = "ZGZS-Expert";//默认显示资格证书
            string certName = string.Empty;
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var list = JsonConvert.DeserializeObject<List<ModelService.Tb_Emp_TitleDetails>>(client.GetEmpQualities(empGuid, areaCode));
                list=list.Where(q => q.StampCode == type).OrderBy(q=>q.CertificateCode).ThenBy(q=>q.CertificateLevel).ToList();
                RepQualitie.DataSource = list;
                RepQualitie.DataBind();
                foreach (var l in list)
                {
                    string clCode="";
                    if (l.CertificateName.Trim() != certName)
                    {
                        if (l.CLCode != "不分等级" && l.CLCode!="请选择")
                        {
                            clCode = l.CLCode;
                        }
                        if (lblZS.Text.Length > 2)
                        {
                            lblZS.Text += "<br/>";
                        }
                        lblZS.Text += l.CertificateName + " " + clCode ;
                       
                        certName = l.CertificateName.Trim();
                    }
                }
            }
        }
        /// <summary>
        /// 人员主要工作经历查询
        /// </summary>
        private void GetWorkExperience(string empGuid, string areaCode)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var list = JsonConvert.DeserializeObject<List<ModelService.tb_WorkExperience>>(client.GetWorkExperienceList(empGuid, areaCode));
                RepWork.DataSource = list;
                RepWork.DataBind();
            }
        }

        /// <summary>
        /// 专家关系单位，关系专家
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        private void GetExpertRelation(string empGuid, string areaCode)
        {
            RepDanwei.DataSource = GetExpertRelationList(empGuid, areaCode,1);
            RepDanwei.DataBind();
            RepZhuanjia.DataSource = GetExpertRelationList(empGuid, areaCode, 0);
            RepZhuanjia.DataBind();
        }
        /// <summary>
        /// 专家关系单位，关系专家
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="context"></param>
        private List<ModelService.tb_User_Relation> GetExpertRelationList(string empGuid, string areaCode, int flag)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                return JsonConvert.DeserializeObject<List<ModelService.tb_User_Relation>>(client.GetUserRelationList(empGuid, flag, areaCode));
            }
        }

        /// <summary>
        /// 专家专业
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        private void GetExpertSpecialityList(string empGuid, string areaCode)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var list = JsonConvert.DeserializeObject<List<ModelService.tb_Expert_Speciality>>(client.GetExpertSpecialityList(empGuid, areaCode));
               var list1 = list.Where(o => o.IsMain != null && o.IsMain == true).ToList();
               var list2 = list.Where(o => o.IsMain != null && o.IsMain == false).OrderBy(o=>o.ID).ToList();
               if (list1 != null && list1.Count > 0)
               {
                   lblZy1.Text = list1.Select(l => l.SpecialityName).FirstOrDefault();
               }
               if (list2 != null && list2.Count > 0)
               {
                   var lblTxt = list2.Select(l => l.SpecialityName).ToList();
                   lblZy2.Text = lblTxt[0];
                   if (lblTxt.Count > 1)
                   {
                       lblZy3.Text = lblTxt[1];
                   }
               }
            }
        }

        /// <summary>
        /// 取得专家导出pdf替换数据
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="context"></param>
        private void ExportPdf(string empGuid, string areaCode, string corpGuid, string empName)
        {
            string sysCodes = "EF,EF,EF,EF";
            string funcCodes = "PersonID,PersonZC,PersonSign,PersonZG";
            string funcName = "身份证扫描件,职称扫描件,签名扫描件,资格证书扫描件";
            ////组合替换数据
            Dictionary<string, string> dict = new Dictionary<string, string>();
            lblEmpName.Text=empName;
            lblCompanyName.Text=GetCompanyName(corpGuid, areaCode);
            //取得上传文件参数
            if (!string.IsNullOrEmpty(sysCodes) && !string.IsNullOrEmpty(funcCodes))
            {
                string[] sCodes = sysCodes.TrimEnd(',').Split(',');
                string[] fCodes = funcCodes.TrimEnd(',').Split(',');
                string[] funcNames = funcName.Split(',');
                string url = string.Empty;
              
                List<JsonEntity> imgs = new List<JsonEntity>();
                FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient();
                {
                    for (int i = 0; i < sCodes.Length; i++)
                    {
                        if (string.IsNullOrEmpty(sCodes[i]) || string.IsNullOrEmpty(fCodes[i]))
                        {
                            continue;
                        }
                        ///判断是否有上传扫描件
                        if (fileService.GetFileList(empGuid, sCodes[i], fCodes[i]).Count > 0)
                        {
                            url = ImgBrowseUrl + "?fileName=" + empGuid + ".jpg&gettype=last&sysCode=EF&funcCode=" + fCodes[i] + "&rand=" + Guid.NewGuid().ToString();
                            JsonEntity entity = new JsonEntity();
                            entity.key = url;
                            entity.value = funcNames[i];
                            imgs.Add(entity);
                        } 
                       
                    }
                }
                /////资格证书
                if (fCodes.Contains("PersonZG"))
                {
                    string zsGuid = GetEmpQualitiesGuid(empGuid, areaCode);
                    if (!string.IsNullOrEmpty(zsGuid) )
                    {
                        JsonEntity entity1 = new JsonEntity();
                        entity1.key = ImgBrowseUrl + "?fileName=" + zsGuid + ".jpg&sysCode=EF&funcCode=PersonZG&rand=" + Guid.NewGuid().ToString();
                        entity1.value = "资格证书扫描件";
                        imgs.Add(entity1);
                    }
                }
                RepImgs.DataSource = imgs;
                RepImgs.DataBind();
            }
          
        }

        /// <summary>
        /// 返回有证书图片的证书Guid
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetEmpQualitiesGuid(string empGuid, string areaCode)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var zslist = JsonConvert.DeserializeObject<List<ModelService.Tb_Emp_TitleDetails>>(client.GetEmpQualities(empGuid, areaCode));
                if (zslist != null && zslist.Count > 0)
                {
                    var guids = zslist.Where(q => q.StampCode == "ZGZS-Expert").Select(z => z.EducationGUID).ToList();
                    FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient();
                    {
                        for (int i = 0; i < guids.Count; i++)
                        {
                            ///判断是否有上传扫描件
                            if (fileService.GetFileList(guids[i].ToString(), "EF", "PersonZG").Count > 0)
                            {
                                return guids[i].ToString();
                            }
                        }
                    }
                }
                return string.Empty;
            }
        }

        /// <summary>
        /// 返回专家单位名称
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private string GetCompanyName(string corpUserGuid, string areaCode)
        {
            try
            {
                ////获取单位信息
                using (EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient())
                {
                    List<ModelService.QueryCompanyInfoCondition> queryCompanyInfoList = new List<ModelService.QueryCompanyInfoCondition>() 
                   {
                      new ModelService.QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } }
                   };
                    var jcorp = enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), areaCode);
                    var corpInfo = JsonConvert.DeserializeObject<ModelService.Tb_Corp_CompanyInfo>(jcorp);

                    return corpInfo.CorpName;
                }
            }
            catch { }
            return string.Empty;

        }
    }
}